package com.example.doctorsystem.dao;

import com.example.doctorsystem.model.Announcement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class AnnouncementDaoImpl implements AnnouncementDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int addAnnouncement(Announcement announcement) {
        String sql = "INSERT INTO announcements (title, content) VALUES (?, ?)";
        return jdbcTemplate.update(sql, announcement.getTitle(), announcement.getContent());
    }

    @Override
    public List<Announcement> getAllAnnouncements() {
        String sql = "SELECT * FROM announcements ORDER BY created_time DESC";
        return jdbcTemplate.query(sql, new RowMapper<Announcement>() {
            @Override
            public Announcement mapRow(ResultSet rs, int rowNum) throws SQLException {
                Announcement a = new Announcement();
                a.setId(rs.getInt("id"));
                a.setTitle(rs.getString("title"));
                a.setContent(rs.getString("content"));
                a.setCreatedTime(rs.getTimestamp("created_time").toLocalDateTime());
                return a;
            }
        });
    }

    @Override
    public int deleteAnnouncementById(int id) {
        String sql = "DELETE FROM announcements WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }
}

